package com.qiezikaka.kaka.ui.single;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qiezikaka.kaka.R;
import com.qiezikaka.kaka.adapter.FuZhuangDataListAdapter;
import com.qiezikaka.kaka.base.BaseActivity;
import com.qiezikaka.kaka.bean.FuZhuangInfo;
import com.qiezikaka.kaka.bean.UpdataVersionInfo;
import com.qiezikaka.kaka.common.Common;
import com.qiezikaka.kaka.databinding.ActivityStyleSingleBinding;
import com.qiezikaka.kaka.ui.StyleChoiceAllActivity;
import com.qiezikaka.kaka.ui.detail.DetailCameraFaceTakleActivity;
import com.qiezikaka.kaka.ui.scan.ScanCodeActivity;
import com.qiezikaka.kaka.view.GridSpacingItemDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import util.UpdateAppUtils;

/**
 * 风格选择
 */
public class StyleSingleActivity extends BaseActivity<StyleSinglePresenter> implements View.OnClickListener, StyleSingleContract.View, BaseQuickAdapter.OnItemClickListener {

    ActivityStyleSingleBinding mBinding;
    private StyleSinglePresenter presenter;
    private int PAGE_NO = 1;
    private int PAGE_SIZE = 10;
    private String cateId = "1";
    private boolean isFristLoad = true;
    private FuZhuangDataListAdapter hotDataAdapter;
    private boolean hasLoadMore = false;

    @Override
    public View getLayout() {
        mBinding = ActivityStyleSingleBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @Override
    protected StyleSinglePresenter getPresenter() {
        if (presenter == null) {
            presenter = new StyleSinglePresenter(this, this);
        }
        return presenter;
    }

    @Override
    protected void initEventAndData() {
        initData();
        initView();
        initCountDown();
        presenter.getGoodsList(cateId, PAGE_NO + "", PAGE_SIZE + "", "0");
    }

    private CountDownTimer countDownTimer;

    private void initCountDown() {
        // 设置倒计时 10秒
        countDownTimer = new CountDownTimer(Common.CountDownTime, 1000) { // 10秒倒计时，每1秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                // 可以更新UI，显示剩余时间
                // 例如：textView.setText("倒计时：" + millisUntilFinished / 1000);
                mBinding.tvCountDownTime.setText("" + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                // 倒计时结束后退出页面
                finish(); // 可选，结束当前Activity
            }
        };
        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 确保倒计时被取消
        }
    }

    private void initData() {
        Intent intent = getIntent();
        cateId = intent.getStringExtra("cateId");
        presenter.updateVersion();

        if ("1".equals(cateId)) { // 男人
            mBinding.styleSingleRoot.setBackgroundResource(R.mipmap.style_single_03);
            mBinding.ivStyleName.setImageResource(R.mipmap.style_name_man);
        } else if ("2".equals(cateId)) { // 女人
            mBinding.styleSingleRoot.setBackgroundResource(R.mipmap.style_single_02);
            mBinding.ivStyleName.setImageResource(R.mipmap.style_name_lady);
        } else if ("3".equals(cateId)) { //小孩姐
            mBinding.styleSingleRoot.setBackgroundResource(R.mipmap.style_single_04);
            mBinding.ivStyleName.setImageResource(R.mipmap.style_name_boy);
        } else if ("4".equals(cateId)) { // 小孩姐
            mBinding.styleSingleRoot.setBackgroundResource(R.mipmap.style_single_01);
            mBinding.ivStyleName.setImageResource(R.mipmap.style_name_girl);
        }
    }

    private void initView() {
        mBinding.ivBack.setOnClickListener(this);
        mBinding.rvHot.setLayoutManager(new GridLayoutManager(this, 3));
        mBinding.rvHot.addItemDecoration(new GridSpacingItemDecoration(3, 32, false));

        mBinding.refreshHot.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                PAGE_NO = 1;
                presenter.getGoodsList(cateId, PAGE_NO + "", PAGE_SIZE + "", "0");
                hasLoadMore = false;
            }
        });

        mBinding.refreshHot.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                ++PAGE_NO;
                presenter.getGoodsList(cateId, PAGE_NO + "", PAGE_SIZE + "", "0");
                hasLoadMore = true;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onGoodsList(FuZhuangInfo info) {
        mBinding.refreshHot.finishLoadMore();
        mBinding.refreshHot.finishRefresh();
        mBinding.refreshHot.resetNoMoreData();//setNoMoreData(false);
        switch (info.getStatus()) {
            case 200:
                FuZhuangInfo.DataBean infoData = info.getData();
                if (infoData != null) {
                    int page = infoData.getPage();
                    if (isFristLoad) {
                        List<FuZhuangInfo.DataBean.ListBean> list = infoData.getList();
                        hotDataAdapter = new FuZhuangDataListAdapter(R.layout.item_goods, list); //item_hot_fuzhuang
                        mBinding.rvHot.setAdapter(hotDataAdapter);
                        hotDataAdapter.setOnItemClickListener(this::onItemClick);
                        isFristLoad = false;

                    } else {
                        if (!hasLoadMore) { //上拉加载
                            List<FuZhuangInfo.DataBean.ListBean> dataList = infoData.getList();
                            hotDataAdapter.replaceData(dataList);

                        } else { //下拉刷新
                            if (PAGE_NO <= page) {
                                //说明有值
                                List<FuZhuangInfo.DataBean.ListBean> dataList = infoData.getList();
                                hotDataAdapter.addData(dataList);
                            }
                        }
                    }
                    List<FuZhuangInfo.DataBean.ListBean> listBeanList = hotDataAdapter.getData();
                    if (listBeanList != null && listBeanList.size() != 0) {
                        mBinding.rvHot.setVisibility(View.VISIBLE);
                        mBinding.emptyHot.clEmpty.setVisibility(View.GONE);
                    } else {
                        mBinding.rvHot.setVisibility(View.GONE);
                        mBinding.emptyHot.clEmpty.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case 422:
                showToast(info.getMessage());
                break;
            default:
                break;
        }
    }

    @Override
    public void onFailer(Throwable throwable) {
        mBinding.refreshHot.finishLoadMore();
        mBinding.refreshHot.finishRefresh();
        mBinding.refreshHot.resetNoMoreData();//setNoMoreData(false);
    }

    @Override
    public void onUpdataApp(UpdataVersionInfo InfoData) {
        switch (InfoData.getStatus()) {
            case 200:
                UpdataVersionInfo.DataBean data = InfoData.getData();
                if (data != null) {
                    String apk_file_url = data.getApk_url();
                    String is_must = data.getIs_must();//是否强制升级
                    int version_code = data.getVersion_code();
                    String update_log = data.getUpdate_log();
                    String new_version = data.getVersion_str();

                    String log = "优化了用户体验";
                    if (!TextUtils.isEmpty(update_log)) {
                        String[] split = update_log.split("&");
                        for (int i = 0; i < split.length; i++) {
                            log = log + "\n" + split[i];
                        }
                    }
                    boolean ismust = "1".equals(is_must);

                    UpdateAppUtils.from(this)
                            .serverVersionCode(version_code)
                            .serverVersionName(new_version)
                            .apkPath(apk_file_url)
                            .updateInfo(log)
                            .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载。默认app下载
                            .showNotification(true)
                            .isForce(false) //是否强制更新
//                                .needFitAndroidN(false)
                            .update();
                }
                break;
            case 422:
                showToast(InfoData.getMessage());
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        List<FuZhuangInfo.DataBean.ListBean> list = adapter.getData();
        if (list != null && list.size() != 0) {
            FuZhuangInfo.DataBean.ListBean listBean = list.get(position);
            if (listBean != null) {
                String id = listBean.getId();
                Intent mIntent = new Intent(this, DetailCameraFaceTakleActivity.class);
                mIntent.putExtra("pid", id);
                startActivity(mIntent);
            }
        }
    }


}
